//
//  ImageAudioSequenceViewController.m
//  SadTrombone
//
//  Created by Demis Bellot on 19/04/2009.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "ImageAudioSequenceViewController.h"
#import "UXUI.h";
#import "UXSystem.h";

#define LOGGER 1 << 20
#define DEFAULT_SEQUENCE_INTERVAL 0.375f
#define LAST_SEQUENCE_INTERVAL 0.375f

@implementation ImageAudioSequenceViewController

@synthesize images;
@synthesize playButton;
@synthesize audioFileName;
@synthesize sequenceTimer;
@synthesize imageView;
@synthesize sequenceInterval;
@synthesize lastSequenceInterval;
@synthesize autoPlay;

- (id)initWithCoder:(NSCoder *)coder {	
	if (self = [super initWithCoder:coder]) {
		DLog(@"initializing");
		
		NSMutableArray* aArray = [[[NSMutableArray alloc] init] retain];
		images = aArray;
		[aArray release];
		sequenceInterval = DEFAULT_SEQUENCE_INTERVAL;
		lastSequenceInterval = LAST_SEQUENCE_INTERVAL;
	}
	return self;
}

- (void)setImageNames:(NSMutableArray*)imageNames 
	sequenceBehaviour:(SequenceBehaviour)imageSequenceBehaviour
		audioFileName:theAudioFileName
		   playButton:(UIButton*)aPlayButton
{
	self.audioFileName = theAudioFileName;
	
	DLog(@"setting image sequence");
	for (NSString* imageName in imageNames)
	{
		SLog(@"setting imageName %@", imageName);
		[images addObject:[UIImage imageNamed:imageName]];
	}	
	
	SLog(@"loaded initial %d image sequences. behaviour = %d", [images count], imageSequenceBehaviour);
	if (imageSequenceBehaviour == SequenceBehaviourReverseAtEnds)
	{
		//add reverse images
		for (int i=[images count]-1; i>0; i--) {
			UIImage* reverseStepImage = [images objectAtIndex:i];
			[images addObject:reverseStepImage];
		} 
	}
	SLog(@"loaded %d total image sequences", [images count]);
	
	SLog(@"loading first image");
	UIImage* firstImage = [images objectAtIndex:0];	
	UIImageView* aImageView = [[UIImageView alloc] initWithImage:firstImage];
	imageView = aImageView;
	[self.view addSubview:imageView];
	[aImageView release];	
	
	self.playButton = aPlayButton;
 	[playButton addClickHandler:@selector(play) forTarget:self];
	[self.view addSubview:playButton];
}

- (void)viewDidLoad {
	DLog(@"autoplaying: %@", boolToString(autoPlay));
	
	if (autoPlay)
	{
		[self play];
		[super viewDidLoad];
	}
}

- (void)play {
	DLog(@"playButton: %@", playButton);
	
	playButton.selected = TRUE;
	playButton.userInteractionEnabled = FALSE;
	
	[self restart];
	[self playAudio];
	
	NSDate* date = [NSDate date];
	NSDate* now = [date addTimeInterval:0];
	NSTimer* timer = [[NSTimer alloc] initWithFireDate:now interval:sequenceInterval target:self selector:@selector(playSequence:) userInfo:nil repeats:YES];
	self.sequenceTimer = timer;
	[[NSRunLoop currentRunLoop] addTimer:self.sequenceTimer forMode:NSDefaultRunLoopMode];
	
	[timer release];
}

- (BOOL)hasAudio {
	return self.audioFileName != NULL;
}

- (void) playAudio {
	DLog(@"playAudio: %@", boolToString([self hasAudio]));
	
	if (![self hasAudio]) return;
	
	if (audioPlayer) 
	{
		SLog(@"restarting player");
		[audioPlayer stop];		
		[audioPlayer play];	
		return;
	}
	
	NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingFormat:@"/%@",audioFileName];
	SILog(LOGGER, @"Path to play: %@", resourcePath);
	NSError* err;
	
	//Initialize our player pointing to the path to our resource
	audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:resourcePath] error:&err];
	
	if (err)
	{
		SELog(LOGGER, @"Failed with reason: %@", [err localizedDescription]);
	}
	else
	{
		//set our delegate, flip the button and let the magic happen
		audioPlayer.delegate = self;
		[audioPlayer play];
	}	
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)aplayer successfully:(BOOL)flag {
	[audioPlayer stop];
	
	//If they don't want a delay then resetPlayer immediately
	if (lastSequenceInterval == 0)
	{
		[self restart];
		[self resetPlayer];
		return;
	}
	
	NSTimer* timer = [[NSTimer alloc] initWithFireDate:[[NSDate date] addTimeInterval:lastSequenceInterval] 
											  interval:0.0f 
												target:self selector:@selector(restart) 
											  userInfo:nil repeats:NO];
	[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
	[timer release];
	
	timer = [[NSTimer alloc] initWithFireDate:[[NSDate date] addTimeInterval:lastSequenceInterval*2] 
											  interval:0.0f 
												target:self selector:@selector(resetPlayer) 
											  userInfo:nil repeats:NO];
	[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
	[timer release];
}

- (void)resetPlayer {
	playButton.selected = FALSE;
	playButton.userInteractionEnabled = TRUE;
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
	SLog(@"Error while decoding: %@", [error localizedDescription] );
}

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
	DLog(@"Interrupted!");
}

- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player {
	DLog(@"EndInterruption!");
}

- (void)disposeAudioPlayer {
	if (audioPlayer) 
	{
		[audioPlayer stop];
		[audioPlayer release];
		audioPlayer = nil;
	}	
}

- (void) restart {
	sequenceNumber = 0;
	imageView.image = [self currentImage];
}

- (void) nextSequence {
	sequenceNumber++;
	imageView.image = [self currentImage];
}

- (UIImage*) currentImage {
	NSInteger imageIndex = sequenceNumber % [images count];
	SLog(@"getting image for sequenceNumber %d mod %d at index %d", sequenceNumber, [images count], imageIndex);
	return [images objectAtIndex:imageIndex];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

- (void) playSequence:(NSTimer*)timer {
	
	if (!audioPlayer.playing) 
	{
		[sequenceTimer invalidate];
		sequenceTimer = NULL;
		return;
	}
	
	[self nextSequence];
}

- (void)dealloc {
	[images release];
	[self disposeAudioPlayer];
	[playButton release];
	[audioFileName release];
	[sequenceTimer dealloc];
    [super dealloc];
}


@end
